<template>
    <!-- 订单详情 -->
    <div style="height: 80px; width: 100%" class="flex flex-wrap items-center gap-2">
        <!-- 行高 -->
        <el-tooltip effect="dark" content="调整行高" placement="bottom">
            <el-input-number style="width: 120px" v-model="rowHeight" :min="60" :max="120" :step="10" step-strictly />
        </el-tooltip>
        <el-text type="primary" tag="b">{{ '订单号：' + order.orderNo + ' | ' }}</el-text>
        <el-text type="primary" tag="b">{{ '总金额：' + order.orderAmount }}</el-text>
        <el-button type="primary" :icon="RowInsert" @click="addOrderDetail">增加</el-button>
        <el-button type="danger" :icon="RowDelete" @click="deleteOrderDetail">删除</el-button>
        <el-button v-if="order.orderTax" type="warning" :icon="SwitchHorizontal" @click="changeOrderTax(false)">切换不含税</el-button>
        <el-button v-if="!order.orderTax" type="warning" :icon="SwitchHorizontal" @click="changeOrderTax(true)">切换含税</el-button>
        <el-button type="primary" :icon="ChangeCatalog" @click="openOrderDeliveryDateDialog">变更送货计划</el-button>
        <!-- 验证是否已经添加过订单处理 -->
        <el-popconfirm v-if="order.orderProcess" width="200" title="当前订单已经添加过订单处理，是否重复添加？" @confirm="processOrderEvent">
            <template #reference>
                <el-button type="info" :icon="DocumentWordProcessor">订单处理</el-button>
            </template>
        </el-popconfirm>
        <el-button v-if="!order.orderProcess" type="info" :icon="DocumentWordProcessor" @click="processOrderEvent">订单处理</el-button>
        <el-button :disabled="saveDisable" :type="saveType" :icon="Save" @click="saveOrderDetailEvent">保存</el-button>
    </div>
    <!-- 表格展示 -->
    <div style="height: calc(100vh - 160px); width: 100%">
        <el-auto-resizer>
            <template #default="{ height, width }">
                <FTableV2
                    v-model="selected"
                    :data="data"
                    :width="width"
                    :height="height"
                    :row-height="rowHeight"
                    :other-column="otherColumn"
                    :disable="disable"
                ></FTableV2>
            </template>
        </el-auto-resizer>
    </div>

    <!-- 变更采购送货日期弹窗 -->
    <el-dialog v-model="orderDeliveryDateVisible" :close-on-click-modal="false" :show-close="false">
        <!-- 自定义标题 -->
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">变更所有勾选的送货日期</h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
                    关闭
                </el-button>
            </div>
        </template>
        <!-- 自定义内容 -->
        <div class="flex gap-2">
            <el-date-picker v-model="orderDeliveryDate" type="date" placeholder="请选择日期" />
            <el-button type="primary" @click="updateOrderDeliveryDateEvent">确认</el-button>
        </div>
    </el-dialog>
</template>

<script setup lang="tsx">
import { Column, ElAutocomplete, ElButton, ElInput, ElInputNumber, ElTooltip } from 'element-plus';
import { CircleCloseFilled } from '@element-plus/icons-vue';
import { getProductList } from '@api/product';
import { getOrderDetail, updateOrder, updateOrderDeliveryDate, updateOrderDetail } from '@api/order';
import { FunctionalComponent } from 'vue';
import { formatTimeZone, KeepTwoDecimalPlaces } from '@/utils/calculate';
import { useOrderStore } from '@/store/modules/order';
import { RowInsert, RowDelete, DocumentWordProcessor, Save, ChangeCatalog } from '@vicons/carbon';
import { SwitchHorizontal } from '@vicons/tabler';

onMounted(() => {
    getOrderDetailEvent();
});

/* ******************************父组件属性/方法****************************** */
// 父组件传来的属性
type Props = {
    customerInfo: {
        customerId: string;
        customerName: string;
        customerAbbreviation: string;
    };
};
const props = defineProps<Props>();
// 父组件传来的model
const orderId = defineModel<string>({ required: true });
// 监听父组件数据变化
watch(
    () => orderId.value,
    () => {
        getOrderDetailEvent();
    }
);

/* ******************************通用属性/方法****************************** */
// 组件实例
const instance = getCurrentInstance();
// 订单数据
const order = ref<AjaxResponse['orderList'][0]>({} as any);
// 展示的订单数据
const data = reactive<AjaxResponse['orderList'][0]['orderDetail']>([]);
// 产品库数据
const productList = reactive<AjaxResponse['productList']>([]);
// 获取清单详情数据
const getOrderDetailEvent = () => {
    // 加载产品库数据
    getProductList(props.customerInfo.customerId).then((res) => {
        // 清零产品库
        productList.length = 0;
        // 加载产品库
        res.data.forEach((item) => {
            // 筛选可用产品
            if (item.productAvailable) {
                item.value = item.productName;
                productList.push(item);
            }
        });
    });
    // 加载选中，每次父组件点击某订单，都重新加载
    getOrderDetail(orderId.value).then((res) => {
        // 清空数据
        data.length = 0;
        // 赋值
        order.value = res.data;
        order.value.orderDetail.forEach((item, index) => {
            // @ts-ignore
            item.checked = false;
            // @ts-ignore
            item.order = index + 1;
            // @ts-ignore
            item.editing = false;
            item.remark = '';
            data.push(item);
        });
    });
};

/* ******************************tablev2属性/方法****************************** */
// 表格被选择的数据
const selected = reactive<string[]>([]);
// // 表格高度
const rowHeight = ref(60);
// 自定义组件
type AutoCompleteCellProps = {
    value: string;
    disable: boolean;
    fetchSuggestions: (value: string, cb: Function) => void;
    onInput: (value: string) => void;
    onSelect: (item: any) => void;
    onClear: () => void;
};
const AutoCompleteCell: FunctionalComponent<AutoCompleteCellProps> = ({ value, disable, fetchSuggestions, onSelect, onClear }) => {
    return (
        <ElAutocomplete modelValue={value} disable={disable} clearable fetchSuggestions={fetchSuggestions} onSelect={onSelect} onClear={onClear} />
    );
};
// 自定义column
const otherColumn = reactive<{ [key: string]: Column<any> }>({
    // 重写覆盖字典的materialNumber
    materialNumber: {
        key: 'materialNumber',
        dataKey: 'materialNumber',
        width: 180,
        title: '物料号',
        align: 'center',
        cellRenderer: ({ rowData }) => {
            return <div>{rowData.materialNumber}</div>;
        },
    },
    // 重写覆盖字典的productName
    productName: {
        key: 'productName',
        dataKey: 'productName',
        width: 200,
        title: '产品名称',
        align: 'center',
        cellRenderer: ({ rowData }) => {
            // 清空输入框
            const onClear = () => {
                if (rowData.deliveryQuantity > 0) {
                    ElMessage({
                        message: '已发货产品不允许修改产品名称',
                        type: 'warning',
                        grouping: true,
                    });
                    getOrderDetailEvent();
                    return;
                }
            };
            // 数据变化
            const onInput = (value: string) => {
                if (rowData.deliveryQuantity > 0) {
                    ElMessage({
                        message: '已发货产品不允许修改产品名称',
                        type: 'warning',
                        grouping: true,
                    });
                    getOrderDetailEvent();
                    return;
                }
                rowData.productName = value;
            };
            // 查询搜索
            const fetchSuggestions = (queryString: string, cb: any) => {
                // 条件过滤
                if (productList.length == 0) {
                    // 没有该订单客户的产品
                    ElMessage({
                        message: '没有该客户的产品库',
                        type: 'warning',
                        grouping: true,
                    });
                    cb([{}]);
                } else {
                    // 创建过滤器
                    const createFilter = (queryString: string) => {
                        return (product: any) => {
                            // 匹配产品名称
                            return new RegExp(queryString.toLowerCase()).test(product.productName.toLowerCase());
                        };
                    };
                    // 匹配数据
                    const results = queryString ? productList.filter(createFilter(queryString)) : productList;
                    cb(results);
                }
            };

            // 选择事件
            const onSelect = (item: (typeof productList)[0]) => {
                if (rowData.deliveryQuantity > 0) {
                    ElMessage({
                        message: '已发货产品不允许修改产品名称',
                        type: 'warning',
                        grouping: true,
                    });
                    getOrderDetailEvent();
                    return;
                }
                // 基本数据替换
                rowData.productId = item._id;
                rowData.materialNumber = item.materialNumber;
                rowData.productName = item.productName;
                rowData.productSize = item.productSize;
                rowData.excludTaxPrice = item.excludTaxPrice;
                rowData.includeTaxPrice = item.includeTaxPrice;
                rowData.remark = item.remark;
                // 重新计算小计
                if (order.value.orderTax) {
                    rowData.subtotal = KeepTwoDecimalPlaces(rowData.includeTaxPrice * rowData.orderNumber);
                } else {
                    rowData.subtotal = KeepTwoDecimalPlaces(rowData.excludTaxPrice * rowData.orderNumber);
                }
                // 重新计算总计
                order.value.orderAmount = KeepTwoDecimalPlaces(order.value.orderDetail.reduce((acc, curr) => acc + curr.subtotal, 0));
                // 保存按钮的disable
                saveDisable.value = false;
            };

            /**
             * value 产品名称
             * disable 送过货的row禁止修改
             */
            return (
                <AutoCompleteCell
                    value={rowData.productName}
                    disable={rowData.deliveryQuantity > 0 ? true : false}
                    fetchSuggestions={fetchSuggestions}
                    onInput={onInput}
                    onSelect={onSelect}
                    onClear={onClear}
                />
            );
        },
    },
    // orderNumber
    orderNumber: {
        key: 'orderNumber',
        dataKey: 'orderNumber',
        width: 110,
        title: '订单数量',
        align: 'center',
        cellRenderer: ({ rowData }) => {
            // 订单数量变化
            const onInput = (value: string) => {
                if (rowData.deliveryQuantity > 0) {
                    ElMessage({
                        message: '已发货产品不允许修改产品名称',
                        type: 'warning',
                        grouping: true,
                    });
                    getOrderDetailEvent();
                    return;
                }
                rowData.orderNumber = Number(value);
                // 重新计算小计
                if (order.value.orderTax) {
                    rowData.subtotal = KeepTwoDecimalPlaces(rowData.includeTaxPrice * rowData.orderNumber);
                } else {
                    rowData.subtotal = KeepTwoDecimalPlaces(rowData.excludTaxPrice * rowData.orderNumber);
                }
                // 重新计算总计
                order.value.orderAmount = KeepTwoDecimalPlaces(order.value.orderDetail.reduce((acc, curr) => acc + curr.subtotal, 0));
                // 保存按钮的disable
                saveDisable.value = false;
            };
            return <ElInput type={'number'} modelValue={rowData.orderNumber} onInput={onInput} />;
        },
    },
    // deliveryQuantity
    deliveryQuantity: {
        key: 'deliveryQuantity',
        dataKey: 'deliveryQuantity',
        width: 110,
        title: '送货数量',
        align: 'center',
    },
    // excludTaxPrice
    excludTaxPrice: {
        key: 'excludTaxPrice',
        dataKey: 'excludTaxPrice',
        width: 100,
        title: '不含税单价',
        align: 'center',
        cellRenderer: ({ rowData }) => {
            // 不含税单价变化
            const onInput = (value: string) => {
                if (rowData.deliveryQuantity > 0) {
                    ElMessage({
                        message: '已发货产品不允许修改产品名称',
                        type: 'warning',
                        grouping: true,
                    });
                    getOrderDetailEvent();
                    return;
                }
                rowData.excludTaxPrice = Number(value);
                // 重新计算小计
                if (order.value.orderTax) {
                    rowData.subtotal = KeepTwoDecimalPlaces(rowData.includeTaxPrice * rowData.orderNumber);
                } else {
                    rowData.subtotal = KeepTwoDecimalPlaces(rowData.excludTaxPrice * rowData.orderNumber);
                }
                // 重新计算总计
                order.value.orderAmount = KeepTwoDecimalPlaces(order.value.orderDetail.reduce((acc, curr) => acc + curr.subtotal, 0));
                // 保存按钮的disable
                saveDisable.value = false;
            };
            return <ElInput type={'number'} modelValue={rowData.excludTaxPrice} onInput={onInput} />;
        },
    },
    // includePrice
    includeTaxPrice: {
        key: 'includeTaxPrice',
        dataKey: 'includeTaxPrice',
        width: 100,
        title: '含税单价',
        align: 'center',
        cellRenderer: ({ rowData }) => {
            // 不含税单价变化
            const onInput = (value: string) => {
                if (rowData.deliveryQuantity > 0) {
                    ElMessage({
                        message: '已发货产品不允许修改产品名称',
                        type: 'warning',
                        grouping: true,
                    });
                    getOrderDetailEvent();
                    return;
                }
                rowData.includeTaxPrice = Number(value);
                // 重新计算小计
                if (order.value.orderTax) {
                    rowData.subtotal = KeepTwoDecimalPlaces(rowData.includeTaxPrice * rowData.orderNumber);
                } else {
                    rowData.subtotal = KeepTwoDecimalPlaces(rowData.excludTaxPrice * rowData.orderNumber);
                }
                // 重新计算总计
                order.value.orderAmount = KeepTwoDecimalPlaces(order.value.orderDetail.reduce((acc, curr) => acc + curr.subtotal, 0));
                // 保存按钮的disable
                saveDisable.value = false;
            };
            return <ElInput type={'number'} modelValue={rowData.includeTaxPrice} onInput={onInput} />;
        },
    },
    // subtotal
    subtotal: {
        key: 'subtotal',
        dataKey: 'subtotal',
        width: 120,
        title: '小计',
        align: 'center',
    },
    // remark
    remark: {
        key: 'remark',
        dataKey: 'remark',
        width: 220,
        title: '备注',
        align: 'center',
        cellRenderer: ({ rowData }) => {
            // 备注
            const onInput = (value: string) => {
                rowData.remark = value;
                // 保存按钮的disable
                saveDisable.value = false;
            };
            return <ElInput type={'textarea'} modelValue={rowData.remark} onInput={onInput} />;
        },
    },
    // orderDelivery
    orderDelivery: {
        key: 'orderDelivery',
        dataKey: 'orderDelivery',
        width: 80,
        title: '送货计划',
        align: 'center',
        cellRenderer: ({ rowData }) => {
            // 订单总数
            let totalOrderDelivery = 0;
            // 发货总数
            rowData.orderDelivery.forEach((i) => {
                totalOrderDelivery += i.deliveryQuantity;
            });
            // 送货记录
            let delivery = `<div>
            <b>送货计划：</b>
            ${rowData.orderDeliveryDate == '待定' ? '待定' : formatTimeZone(rowData.orderDeliveryDate, 'YYYY-MM-DD')}</div><div>`;
            if (rowData.orderDelivery.length == 0) {
                delivery += '无送货记录';
            } else {
                rowData.orderDelivery.forEach((item: AjaxResponse['orderList'][0]['orderDetail'][0]['orderDelivery'][0]) => {
                    delivery += `
                        <div style="display: flex; gap: 8px;">
                            <div>送货日期：${formatTimeZone(item.deliveryDate, 'YYYY-MM-DD')}</div>
                            <div>送货数量：${item.deliveryQuantity}</div>
                        </div>
                    `;
                });
            }
            delivery += '</div>';

            return (
                <ElTooltip effect={'orderDetail'} rawContent={true} content={delivery}>
                    {rowData.orderDelivery.length > 0 ? (
                        <ElButton plain text type={totalOrderDelivery >= rowData.orderNumber ? 'success' : 'info'}>
                            {totalOrderDelivery >= rowData.orderNumber ? '已送完' : '未完结'}
                        </ElButton>
                    ) : (
                        <ElButton plain text type={'warning'}>
                            未送货
                        </ElButton>
                    )}
                </ElTooltip>
            );
        },
    },
});
// 自定义禁用属性 -- 根据订单情况去禁用column
const disable = computed(() => {
    return order.value.orderTax ? ['excludTaxPrice'] : ['includeTaxPrice'];
});

/* ******************************选项的属性/方法****************************** */
// 订单详情数据修改后保存
// 保存按钮的disable -- 只有在修改数据后才false
const saveDisable = ref(true);
// 保存按钮的type
const saveType = computed(() => {
    return saveDisable.value ? 'warning' : 'success';
});
// 保存订单详情
const saveOrderDetailEvent = () => {
    updateOrderDetail(order.value._id, order.value.orderTax, order.value.orderAmount, data).then((res) => {
        ElMessage({
            message: res.message,
            type: 'success',
            grouping: true,
        });
        instance?.proxy?.$Bus.emit('updateOrderList');
    });
};

// 切换含税标识
const changeOrderTax = (tax: boolean) => {
    if (order.value.orderStatus) {
        ElMessage({
            message: '该订单处于完结状态，禁止修改',
        });
    } else {
        // 变更含税标识，并重新计算小计
        order.value.orderTax = tax;
        data.forEach((item) => {
            if (order.value.orderTax) {
                item.subtotal = KeepTwoDecimalPlaces(item.includeTaxPrice * item.orderNumber);
            } else {
                item.subtotal = KeepTwoDecimalPlaces(item.excludTaxPrice * item.orderNumber);
            }
        });
        order.value.orderAmount = KeepTwoDecimalPlaces(order.value.orderDetail.reduce((acc, curr) => acc + curr.subtotal, 0));
        // 保存按钮的disable
        saveDisable.value = false;
    }
};

// 订单处理
const processOrderEvent = async () => {
    // 如果未保存拒绝处理
    if (!saveDisable.value) {
        ElMessage({
            message: '请先保存订单详情',
            type: 'warning',
            grouping: true,
        });
        return;
    }

    // 如果没有勾选则全部处理
    if (selected.length == 0) {
        let fail = false;
        // 加工存储的数据
        const _data: any[] = [];
        data.forEach((item) => {
            // 代加工的对象
            const obj = {};
            // 如果有发货记录则拒绝处理发货的订单
            if (item.orderDelivery.length > 0) {
                ElMessage({
                    message: `该订单${item.productName}已送货，已取消处理`,
                    type: 'warning',
                    grouping: true,
                });
                fail = true;
                return;
            } else {
                // 添加productId，方面后续查找，防止productName改名后 找不到
                obj['productId'] = productList.find((i) => i.productName == item.productName)?._id;
                Object.assign(obj, item);
                _data.push(obj);
            }
        });

        // 如果该订单处于未激活状态，则不允许添加
        const _order = await getOrderDetail(orderId.value);
        if (_order.data.available == false) {
            ElMessage({
                message: `该订单处于未激活状态，已取消处理`,
                type: 'warning',
                grouping: true,
            });
            fail = true;
        }

        // 拒绝处理
        if (fail) {
            return;
        }

        // 再次确认
        ElMessageBox({
            type: 'warning',
            title: '系统提示',
            message: h('p', null, [
                h('span', null, '是否将此订单添加至订单处理模块？'),
                h('i', { style: 'color: teal' }, '请注意，该方式为本地处理，并不会上传到服务器，请及时处理，以免过期。'),
            ]),
            showCancelButton: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true;
                    instance.confirmButtonText = '处理中...';
                    updateOrder(orderId.value, 'orderProcess', true).then((res) => {
                        if (res.code === 200) {
                            instance.confirmButtonLoading = false;
                            done();
                        } else {
                            ElMessage({
                                type: 'warning',
                                message: '订单处理标识同步至服务器失败，可以手动同步。',
                            });
                            done();
                        }
                    });
                } else {
                    done();
                }
            },
        }).then(() => {
            useOrderStore().addOrderProcessList(
                order.value._id,
                order.value.customerId,
                order.value.orderNo,
                order.value.orderDate,
                order.value.orderDeliveryDate,
                _data,
                order.value.orderRemark,
                order.value.creator,
                order.value.creatorId
            );
            ElNotification({
                title: '系统提示',
                type: 'success',
                message: `本地订单处理加载完毕。`,
            });
            instance?.proxy?.$Bus.emit('updateOrderList');
        });
    } else {
        // 加工存储的数据
        const _data: any[] = [];
        selected.forEach((item) => {
            // 代加工的对象
            const obj = {};
            // 找到被勾选的数据,并添加
            const detail = data.find((i) => i._id == item);
            // 如果有发货记录则拒绝处理
            if (detail!.orderDelivery.length > 0) {
                ElMessage({
                    message: `该订单${detail!.productName}已送货，已取消处理`,
                    type: 'warning',
                    grouping: true,
                });
            } else {
                // 添加productId，方面后续查找，防止productName改名后 找不到
                obj['productId'] = productList.find((i) => i.productName == detail!.productName)?._id;
                Object.assign(obj, detail);
                _data.push(obj);
            }
        });

        // 如果该订单处于未激活状态，则不允许添加
        const _order = await getOrderDetail(orderId.value);
        if (_order.data.available == false) {
            ElMessage({
                message: `该订单处于未激活状态，已取消处理`,
                type: 'warning',
                grouping: true,
            });
            return;
        }

        // 再次确认
        ElMessageBox({
            type: 'warning',
            title: '系统提示',
            message: h('p', null, [
                h('span', null, '是否将此订单添加至订单处理模块？'),
                h('i', { style: 'color: teal' }, '请注意，该方式为本地处理，并不会上传到服务器，请及时处理，以免过期。'),
            ]),
            showCancelButton: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true;
                    instance.confirmButtonText = '处理中...';
                    updateOrder(orderId.value, 'orderProcess', true).then((res) => {
                        if (res.code === 200) {
                            instance.confirmButtonLoading = false;
                            done();
                        } else {
                            ElMessage({
                                type: 'warning',
                                message: '订单处理标识同步至服务器失败，可以手动同步。',
                            });
                            done();
                        }
                    });
                } else {
                    done();
                }
            },
        }).then(() => {
            useOrderStore().addOrderProcessList(
                order.value._id,
                order.value.customerId,
                order.value.orderNo,
                order.value.orderDate,
                order.value.orderDeliveryDate,
                _data,
                order.value.orderRemark,
                order.value.creator,
                order.value.creatorId
            );
            ElNotification({
                title: '系统提示',
                type: 'success',
                message: `本地订单处理加载完毕。`,
            });
            instance?.proxy?.$Bus.emit('updateOrderList');
        });
    }
};

// 添加一行订单详情
const addOrderDetail = () => {
    if (order.value.orderStatus) {
        ElMessage({
            message: '该订单处于完结状态，禁止修改',
        });
    } else {
        // 多个勾选无法添加
        if (selected.length > 1) {
            ElMessage({
                message: '请先勾选一行后重试',
                type: 'warning',
                grouping: true,
            });
            return;
        }

        // 单个勾选添加
        if (selected.length == 1) {
            // 找到被勾选的数据,并添加一行数据
            for (let index = 0; index < data.length; index++) {
                const detail = data[index];
                if (detail._id == selected[0]) {
                    // 在指定位置添加数据
                    // @ts-ignore
                    data.splice(index + 1, 0, {
                        order: data.length + 1,
                        checked: false,
                        editing: false,
                        productName: '',
                        materialNumber: '',
                        productSize: '',
                        orderNumber: 0,
                        deliveryQuantity: 0,
                        excludTaxPrice: 0,
                        includeTaxPrice: 0,
                        subtotal: 0,
                        remark: '',
                        orderDelivery: [],
                    });
                    // 重新排序
                    data.forEach((item, index) => {
                        item.order = index + 1;
                    });
                    saveDisable.value = false;
                    return;
                }
            }
            return;
        }

        // 在末尾添加
        saveDisable.value = false;
        // @ts-ignore
        data.push({
            order: data.length + 1,
            checked: false,
            editing: false,
            productName: '',
            materialNumber: '',
            productSize: '',
            orderNumber: 0,
            deliveryQuantity: 0,
            excludTaxPrice: 0,
            includeTaxPrice: 0,
            subtotal: 0,
            remark: '',
            orderDelivery: [],
        });
    }
};

// 删除一行订单详情
const deleteOrderDetail = () => {
    if (order.value.orderStatus) {
        ElMessage({
            message: '该订单处于完结状态，禁止修改',
        });
    } else {
        // 如果有送货记录也无法删除
        if (selected.length >= 1) {
            // 循环详情数据
            for (let i = 0; i < data.length; i++) {
                const detail = data[i];

                // 循环勾选数据
                for (let j = 0; j < selected.length; j++) {
                    const id = selected[j];

                    // 找到被勾选的数据,并删除
                    if (detail._id == id) {
                        // 判断是否还有送货记录
                        if (detail.orderDelivery.length > 0) {
                            ElMessage({
                                message: '该订单详情有送货记录，禁止删除',
                                type: 'warning',
                                grouping: true,
                            });
                            return;
                        } else {
                            // 删除数据
                            data.splice(i, 1);
                            i--;
                        }
                    }
                }
            }
            // 重新排序
            data.forEach((item, index) => {
                item.order = index + 1;
            });
            // 保存按钮开启
            saveDisable.value = false;
        } else {
            ElMessage({
                message: '请先勾选一行需要删除的数据！',
                type: 'warning',
                grouping: true,
            });
        }
    }
};

// 变更送货时间弹窗
const orderDeliveryDateVisible = ref(false);
// 变更送货时间的数据
const orderDeliveryDate = ref<Date>();
// 变更送货时间弹窗事件
const openOrderDeliveryDateDialog = () => {
    if (selected.length == 0) {
        ElMessage({
            message: '请先勾选一行需要变动的送货时间数据！',
            type: 'warning',
            grouping: true,
        });
        return;
    }
    ElMessage({
        message: '即将修改采购订单中的送货时间（影响生产规划），请区别订单送货时间！',
        type: 'warning',
        grouping: true,
    });
    orderDeliveryDateVisible.value = true;
};

const updateOrderDeliveryDateEvent = () => {
    if (!orderDeliveryDate.value) {
        ElMessage({ message: '请选择送货时间！', type: 'warning', grouping: true });
        return;
    }
    const productNames: string[] = [];
    for (let index = 0; index < selected.length; index++) {
        const select = selected[index];
        const singleOrder = data.find((item) => item._id == select);
        productNames.push(singleOrder!.productName);
    }
    updateOrderDeliveryDate(order.value.orderNo, productNames, orderDeliveryDate.value).then((res) => {
        ElMessage({
            message: res.message,
            type: 'success',
            grouping: true,
        });
    });
};

/*          */
</script>

<style>
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
</style>
